package com.hq.talk.view.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hq.lib_comview.common.code.CodeStatus;
import com.hq.lib_comview.common.code.Constants;
import com.hq.lib_comview.common.code.IntentCode;
import com.hq.lib_comview.common.code.IntentKey;
import com.hq.lib_comview.common.utils.NetUtil;
import com.hq.lib_comview.common.utils.StringUtils;
import com.hq.lib_comview.common.utils.ToastUtil;
import com.hq.lib_comview.view.scprogress.SVProgressHUD;
import com.hq.talk.R;
import com.hq.talk.common.BaseEvent;
import com.hq.talk.common.ConstantTag;
import com.hq.talk.model.UserInfoModel;
import com.hq.talk.presenter.impl.UserPresenter;
import com.hq.talk.service.BackGroundService;
import com.hq.talk.view.base.BaseCommAty;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.litesuits.common.utils.HexUtil;
import com.litesuits.common.utils.MD5Util;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 描述 ：注册界面
 * 作者 ：hq
 * 时间 ：2017/8/5 08:40
 */
public class RegisterAty extends BaseCommAty {

    @BindView(R.id.id_regist_phone_edit)
    EditText mEditPhone;
    private String mSavePhone;
    @BindView(R.id.id_regist_code_edit)
    EditText mEditCode;
    private String mSaveCode;
    @BindView(R.id.id_regist_pw_edit)
    EditText mEditPw;
    private String mSavePw;
    @BindView(R.id.id_regist_name_edit)
    EditText mEditName;
    private String mSaveName;

    @BindView(R.id.id_send_code_btn)
    Button mBtnCode;

    //倒计时类
    private MyCount mc;

    private UserInfoModel model;

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return super.loadView(inflater, inflater.inflate(R.layout.aty_register, null, false));
    }

    @Override
    public boolean hasDataInPage() {
        return true;
    }

    @Override
    public void initPresenter() {
        presenter = new UserPresenter();
    }

    @Override
    public void initView() {
        setTitleText(getString(R.string.register_title), null);
        if (BackGroundService.time_code != 0) {
            startCount(BackGroundService.time_code);
        }
        mEditPw.setKeyListener(new DigitsKeyListener() {
            @Override
            public int getInputType() {
                return InputType.TYPE_TEXT_VARIATION_PASSWORD;
            }

            @Override
            protected char[] getAcceptedChars() {
                char[] data = getResources().getString(
                        R.string.edit_only_can_input).toCharArray();
                return data;
            }
        });
    }

    public boolean checkData() {
        mSavePhone = mEditPhone.getText().toString().trim();
        mSaveCode = mEditCode.getText().toString().trim();
        mSavePw = mEditPw.getText().toString().trim();
        mSaveName = mEditName.getText().toString().trim();
        if (!StringUtils.isMobile(mSavePhone)) {
            SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_right_phone));
        } else {
            if (StringUtils.isEmpty(mSaveCode)) {
                SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_code));
            } else {
                if (StringUtils.isEmpty(mSavePw) || StringUtils.isNumRic(mSavePw) || StringUtils.isLetterRic(mSavePw) || mSavePw.length() < 6 || mSavePw.length() > 18) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_right_pw));
                } else {
                    if (StringUtils.isEmpty(mSaveName)) {
                        SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_name));
                    } else {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    @OnClick({R.id.id_send_code_btn, R.id.id_register_btn})
    public void onClick(View mView) {
        switch (mView.getId()) {
            case R.id.id_send_code_btn:
                //发送验证码
                mSavePhone = mEditPhone.getText().toString().trim();
                if (!StringUtils.isMobile(mSavePhone)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.input_right_phone));
                    return;
                }
                if (!NetUtil.isNetworkConnected(aty)) {
                    SVProgressHUD.showInfoWithStatus(aty, getString(R.string.no_net_work));
                } else {
                    BackGroundService.countDownCode(Constants.COUNTDOWN * 1000);
                    startCount(Constants.COUNTDOWN * 1000);
                    ((UserPresenter) presenter).sendCode(mSavePhone, 1);
                }
                break;
            case R.id.id_register_btn:
                //注册
                if (checkData()) {
                    ((UserPresenter) presenter).register(mSavePhone, mSaveCode, HexUtil.encodeHexStr(MD5Util.md5(mSavePw)), mSaveName);
                }
                break;
        }
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
        if (null != t) {
            if (TextUtils.equals(tag, ConstantTag.Login.REGISTER_SUCCESS)) {
                // 注册成功
                UserInfoModel model = (UserInfoModel) t;

                BaseEvent event = new BaseEvent();
                event.data = IntentKey.Register.KEY_REGISTER_SUCCESS;
                event.model = model;
                EventBus.getDefault().post(event);

                finish();
            }
        }
    }

    @Override
    public void handlerByPage(int flag1, int flag2, boolean loadMore, String string) {
        if (flag1 == CodeStatus.Gegeneral.DATA_SUCCESS_FULL) {
            //短信验证码获取成功
            ToastUtil.showToast(aty, "短信验证码已发送至手机");
        } else {
            //获取失败
            ToastUtil.showToast(aty, "获取失败");
            mBtnCode.setText(getString(R.string.send_code));
            mBtnCode.setEnabled(true);
            if (mc != null) {
                mc.cancel();
            }
            if (null != BackGroundService.countCode) {
                BackGroundService.countCode.cancel();
            }
            BackGroundService.time_code = 0;
        }
    }

    /**
     * 启动倒计时
     */
    private void startCount(long time) {
        mBtnCode.setEnabled(false);
        if (null != mc) {
            mc.cancel();
            mc = null;
        }
        mc = new MyCount(time, 1000);
        mc.start();
    }

    /**
     * 倒计时类
     */
    public class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mBtnCode.setText(millisUntilFinished / 1000 + getString(R.string.second));
        }

        @Override
        public void onFinish() {
            mBtnCode.setText(getString(R.string.send_code));
            mBtnCode.setEnabled(true);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mc) {
            mc.cancel();
        }
    }
}
